<template>
  <div class="wash-order">
    <!-- 搜索筛选 -->
    <el-card class="search-card">
      <el-form :model="searchForm" inline>
        <el-form-item label="订单号">
          <el-input 
            v-model="searchForm.orderNo" 
            placeholder="请输入订单号" 
            clearable 
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="客户姓名">
          <el-input 
            v-model="searchForm.customerName" 
            placeholder="请输入客户姓名" 
            clearable 
            style="width: 150px"
          />
        </el-form-item>
        <el-form-item label="服务类型">
          <el-select v-model="searchForm.serviceType" placeholder="请选择" clearable>
            <el-option label="干洗" value="dry_clean" />
            <el-option label="水洗" value="water_wash" />
            <el-option label="熨烫" value="ironing" />
            <el-option label="修补" value="repair" />
            <el-option label="染色" value="dyeing" />
          </el-select>
        </el-form-item>
        <el-form-item label="订单状态">
          <el-select v-model="searchForm.status" placeholder="请选择" clearable>
            <el-option label="待处理" value="pending" />
            <el-option label="已接单" value="accepted" />
            <el-option label="处理中" value="processing" />
            <el-option label="质检中" value="quality_check" />
            <el-option label="待取件" value="ready" />
            <el-option label="已完成" value="completed" />
            <el-option label="已取消" value="cancelled" />
          </el-select>
        </el-form-item>
        <el-form-item label="下单时间">
          <el-date-picker
            v-model="searchForm.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <el-icon><Search /></el-icon>
            查询
          </el-button>
          <el-button @click="handleReset">
            <el-icon><Refresh /></el-icon>
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 操作工具栏 -->
    <div class="toolbar">
      <div class="toolbar-left">
        <el-button type="primary" @click="handleCreateOrder">
          <el-icon><Plus /></el-icon>
          新建订单
        </el-button>
        <el-button type="success" @click="handleBatchProcess" :disabled="!selectedRows.length">
          <el-icon><Tools /></el-icon>
          批量处理
        </el-button>
        <el-button type="warning" @click="handleExport">
          <el-icon><Download /></el-icon>
          导出订单
        </el-button>
      </div>
      <div class="toolbar-right">
        <el-radio-group v-model="viewMode" size="small">
          <el-radio-button label="table">列表视图</el-radio-button>
          <el-radio-button label="card">卡片视图</el-radio-button>
        </el-radio-group>
      </div>
    </div>

    <!-- 订单统计 -->
    <el-row :gutter="20" class="stats-row">
      <el-col :span="4">
        <div class="stat-item">
          <div class="stat-number">{{ statistics.total || 0 }}</div>
          <div class="stat-label">总订单数</div>
        </div>
      </el-col>
      <el-col :span="4">
        <div class="stat-item pending">
          <div class="stat-number">{{ statistics.pending || 0 }}</div>
          <div class="stat-label">待处理</div>
        </div>
      </el-col>
      <el-col :span="4">
        <div class="stat-item processing">
          <div class="stat-number">{{ statistics.processing || 0 }}</div>
          <div class="stat-label">处理中</div>
        </div>
      </el-col>
      <el-col :span="4">
        <div class="stat-item ready">
          <div class="stat-number">{{ statistics.ready || 0 }}</div>
          <div class="stat-label">待取件</div>
        </div>
      </el-col>
      <el-col :span="4">
        <div class="stat-item completed">
          <div class="stat-number">{{ statistics.completed || 0 }}</div>
          <div class="stat-label">已完成</div>
        </div>
      </el-col>
      <el-col :span="4">
        <div class="stat-item cancelled">
          <div class="stat-number">{{ statistics.cancelled || 0 }}</div>
          <div class="stat-label">已取消</div>
        </div>
      </el-col>
    </el-row>

    <!-- 订单列表 -->
    <el-card class="table-card">
      <!-- 列表视图 -->
      <el-table
        v-if="viewMode === 'table'"
        v-loading="loading"
        :data="tableData"
        border
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="orderNo" label="订单号" width="150" fixed="left">
          <template #default="{ row }">
            <el-button link @click="handleViewDetail(row)">
              {{ row.orderNo }}
            </el-button>
          </template>
        </el-table-column>
        <el-table-column prop="customerName" label="客户" width="100" />
        <el-table-column prop="customerPhone" label="联系电话" width="120" />
        <el-table-column prop="serviceType" label="服务类型" width="100">
          <template #default="{ row }">
            <el-tag>{{ getServiceTypeText(row.serviceType) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="items" label="衣物清单" min-width="200">
          <template #default="{ row }">
            <div class="item-list">
              <span v-for="(item, index) in row.items.slice(0, 2)" :key="index" class="item-tag">
                {{ item.name }} x{{ item.quantity }}
              </span>
              <span v-if="row.items.length > 2" class="more-items">
                等{{ row.items.length }}件
              </span>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="amount" label="金额" width="100">
          <template #default="{ row }">
            ¥{{ row.amount.toFixed(2) }}
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.status)">
              {{ getStatusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="worker" label="负责人" width="100" />
        <el-table-column prop="createTime" label="下单时间" width="150" />
        <el-table-column prop="expectedTime" label="预期完成" width="150" />
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button link size="small" @click="handleViewDetail(row)">
              详情
            </el-button>
            <el-button 
              link 
              size="small" 
              @click="handleUpdateStatus(row)"
              v-if="canUpdateStatus(row.status)"
            >
              更新状态
            </el-button>
            <el-button link size="small" @click="handleAssignWorker(row)">
              分配
            </el-button>
            <el-dropdown @command="(command) => handleMoreAction(command, row)">
              <el-button link size="small">
                更多<el-icon><ArrowDown /></el-icon>
              </el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item command="track">跟踪进度</el-dropdown-item>
                  <el-dropdown-item command="note">添加备注</el-dropdown-item>
                  <el-dropdown-item command="refund" :disabled="!canRefund(row.status)">
                    申请退款
                  </el-dropdown-item>
                  <el-dropdown-item command="cancel" :disabled="!canCancel(row.status)">
                    取消订单
                  </el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </template>
        </el-table-column>
      </el-table>

      <!-- 卡片视图 -->
      <div v-else class="card-view">
        <el-row :gutter="20">
          <el-col :span="8" v-for="order in tableData" :key="order.id">
            <div class="order-card" :class="{ selected: selectedRows.includes(order) }">
              <div class="card-header">
                <div class="order-info">
                  <div class="order-no">{{ order.orderNo }}</div>
                  <el-tag :type="getStatusType(order.status)" size="small">
                    {{ getStatusText(order.status) }}
                  </el-tag>
                </div>
                <el-checkbox 
                  :model-value="selectedRows.includes(order)"
                  @change="(val) => handleCardSelection(val, order)"
                />
              </div>
              <div class="card-content">
                <div class="customer-info">
                  <span class="customer-name">{{ order.customerName }}</span>
                  <span class="customer-phone">{{ order.customerPhone }}</span>
                </div>
                <div class="service-info">
                  <el-tag>{{ getServiceTypeText(order.serviceType) }}</el-tag>
                  <span class="amount">¥{{ order.amount.toFixed(2) }}</span>
                </div>
                <div class="time-info">
                  <div>下单时间：{{ order.createTime }}</div>
                  <div>预期完成：{{ order.expectedTime }}</div>
                </div>
                <div class="worker-info" v-if="order.worker">
                  负责人：{{ order.worker }}
                </div>
              </div>
              <div class="card-actions">
                <el-button link size="small" @click="handleViewDetail(order)">
                  查看详情
                </el-button>
                <el-button 
                  link 
                  size="small" 
                  @click="handleUpdateStatus(order)"
                  v-if="canUpdateStatus(order.status)"
                >
                  更新状态
                </el-button>
              </div>
            </div>
          </el-col>
        </el-row>
      </div>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="page.current"
          v-model:page-size="page.size"
          :total="page.total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 订单详情对话框 -->
    <!-- <OrderDetailDialog
      v-model:visible="detailDialogVisible"
      :order-id="currentOrderId"
      @refresh="getOrderList"
    /> -->

    <!-- 状态更新对话框 -->
    <!-- <StatusUpdateDialog
      v-model:visible="statusDialogVisible"
      :order="currentOrder"
      @refresh="getOrderList"
    /> -->

    <!-- 工人分配对话框 -->
    <!-- <WorkerAssignDialog
      v-model:visible="assignDialogVisible"
      :order="currentOrder"
      @refresh="getOrderList"
    /> -->

    <!-- 新建订单对话框 -->
    <!-- <CreateOrderDialog
      v-model:visible="createDialogVisible"
      @refresh="getOrderList"
    /> -->
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Search,
  Refresh,
  Plus,
  Tools,
  Download,
  ArrowDown
} from '@element-plus/icons-vue'
import { order, statistics as statisticsApi } from '@/api/wash/index'
// import OrderDetailDialog from './components/OrderDetailDialog.vue'
// import StatusUpdateDialog from './components/StatusUpdateDialog.vue'
// import WorkerAssignDialog from './components/WorkerAssignDialog.vue'
// import CreateOrderDialog from './components/CreateOrderDialog.vue'

const router = useRouter()

// 搜索表单
const searchForm = reactive({
  orderNo: '',
  customerName: '',
  serviceType: '',
  status: '',
  dateRange: []
})

// 页面状态
const loading = ref(false)
const viewMode = ref('table')
const tableData = ref([])
const selectedRows = ref([])

// 分页
const page = reactive({
  current: 1,
  size: 20,
  total: 0
})

// 统计数据
const statistics = reactive({
  total: 0,
  pending: 0,
  processing: 0,
  ready: 0,
  completed: 0,
  cancelled: 0
})

// 对话框状态
const detailDialogVisible = ref(false)
const statusDialogVisible = ref(false)
const assignDialogVisible = ref(false)
const createDialogVisible = ref(false)
const currentOrderId = ref(null)
const currentOrder = ref(null)

// 获取订单列表
const getOrderList = async () => {
  try {
    loading.value = true

    const params = {
      page: page.current - 1, // 后端从0开始
      size: page.size,
      ...searchForm
    }

    // 处理日期范围
    if (searchForm.dateRange && searchForm.dateRange.length === 2) {
      params.startDate = searchForm.dateRange[0]
      params.endDate = searchForm.dateRange[1]
    }

    // 调用真实API获取订单列表
    const [orderResponse, statisticsResponse] = await Promise.all([
      order.list(params),
      statisticsApi.orders()
    ])

    if (orderResponse && orderResponse.data) {
      // 处理后端可能返回的错误响应
      if (orderResponse.data.success === false) {
        console.warn('后端返回错误:', orderResponse.data.message)
        tableData.value = orderResponse.data.content || []
        page.total = orderResponse.data.totalElements || 0
      } else {
        tableData.value = orderResponse.data.content || []
        page.total = orderResponse.data.totalElements || 0
      }

      // 确保每个订单都有必要的字段
      tableData.value = tableData.value.map(order => ({
        ...order,
        items: order.items || [],
        amount: order.amount || order.totalAmount || 0,
        createTime: order.createTime || order.createdAt,
        orderNo: order.orderNo || order.orderNumber
      }))
    }

    if (statisticsResponse && statisticsResponse.data) {
      Object.assign(statistics, statisticsResponse.data)
    }
  } catch (error) {
    console.error('获取订单数据失败:', error)
    ElMessage.error('获取订单列表失败')
    // 设置空数据避免页面错误
    tableData.value = []
    page.total = 0
  } finally {
    loading.value = false
  }
}

// 搜索和重置
const handleSearch = () => {
  page.current = 1
  getOrderList()
}

const handleReset = () => {
  Object.assign(searchForm, {
    orderNo: '',
    customerName: '',
    serviceType: '',
    status: '',
    dateRange: []
  })
  handleSearch()
}

// 分页处理
const handleSizeChange = () => {
  getOrderList()
}

const handleCurrentChange = () => {
  getOrderList()
}

// 选择处理
const handleSelectionChange = (selection) => {
  selectedRows.value = selection
}

const handleCardSelection = (val, order) => {
  if (val) {
    selectedRows.value.push(order)
  } else {
    const index = selectedRows.value.findIndex(item => item.id === order.id)
    if (index > -1) {
      selectedRows.value.splice(index, 1)
    }
  }
}

// 状态相关方法
const getStatusType = (status) => {
  const types = {
    pending: 'warning',
    accepted: 'primary',
    processing: 'primary',
    quality_check: 'info',
    ready: 'success',
    completed: 'success',
    cancelled: 'danger'
  }
  return types[status] || 'info'
}

const getStatusText = (status) => {
  const texts = {
    PENDING: '待确认',
    CONFIRMED: '已确认',
    PICKED_UP: '已取件',
    PROCESSING: '处理中',
    QUALITY_CHECK: '质检中',
    COMPLETED: '已完成',
    DELIVERED: '已送达',
    CANCELLED: '已取消',
    // 兼容小写
    pending: '待确认',
    confirmed: '已确认',
    picked_up: '已取件',
    processing: '处理中',
    quality_check: '质检中',
    completed: '已完成',
    delivered: '已送达',
    cancelled: '已取消'
  }
  return texts[status] || '未知'
}

const getServiceTypeText = (type) => {
  const texts = {
    DRY_CLEANING: '干洗',
    WET_CLEANING: '水洗',
    IRONING: '熨烫',
    REPAIR: '修补',
    SPECIAL_CARE: '特殊护理',
    // 兼容小写和其他格式
    dry_cleaning: '干洗',
    wet_cleaning: '水洗',
    dry_clean: '干洗',
    water_wash: '水洗',
    ironing: '熨烫',
    repair: '修补',
    special_care: '特殊护理',
    dyeing: '染色'
  }
  return texts[type] || '未知'
}

const canUpdateStatus = (status) => {
  return !['completed', 'cancelled'].includes(status)
}

const canRefund = (status) => {
  return ['accepted', 'processing', 'quality_check'].includes(status)
}

const canCancel = (status) => {
  return ['pending', 'accepted'].includes(status)
}

// 操作处理
const handleCreateOrder = () => {
  // 跳转到新建订单页面
  router.push('/wash/order/create')
}

const handleViewDetail = (row) => {
  // 跳转到订单详情页面
  router.push(`/wash/order/detail/${row.id}`)
}

const handleUpdateStatus = (row) => {
  currentOrder.value = row
  statusDialogVisible.value = true
}

const handleAssignWorker = (row) => {
  currentOrder.value = row
  assignDialogVisible.value = true
}

const handleMoreAction = (command, row) => {
  currentOrder.value = row
  
  switch (command) {
    case 'track':
      // 跟踪进度
      break
    case 'note':
      // 添加备注
      break
    case 'refund':
      handleRefund(row)
      break
    case 'cancel':
      handleCancel(row)
      break
  }
}

const handleRefund = async (row) => {
  try {
    await ElMessageBox.confirm('确定要申请退款吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    // 调用退款API
    ElMessage.success('退款申请已提交')
    getOrderList()
  } catch (error) {
    // 用户取消
  }
}

const handleCancel = async (row) => {
  try {
    await ElMessageBox.confirm('确定要取消订单吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    await order.cancel(row.id, { reason: '用户取消' })
    ElMessage.success('订单已取消')
    getOrderList()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('取消订单失败')
    }
  }
}

const handleBatchProcess = () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请选择要处理的订单')
    return
  }
  // 批量处理逻辑
  ElMessage.success('批量处理完成')
}

const handleExport = () => {
  ElMessage.success('导出功能开发中')
}

// 生命周期
onMounted(() => {
  getOrderList()
})
</script>

<style lang="scss" scoped>
.wash-order {
  padding: 20px;
  
  .search-card {
    margin-bottom: 20px;
  }
  
  .toolbar {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    
    .toolbar-left {
      display: flex;
      gap: 10px;
    }
  }
  
  .stats-row {
    margin-bottom: 20px;
    
    .stat-item {
      text-align: center;
      padding: 20px;
      background: #fff;
      border-radius: 8px;
      box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
      
      .stat-number {
        font-size: 24px;
        font-weight: bold;
        color: #333;
        margin-bottom: 5px;
      }
      
      .stat-label {
        font-size: 14px;
        color: #666;
      }
      
      &.pending .stat-number { color: #e6a23c; }
      &.processing .stat-number { color: #409eff; }
      &.ready .stat-number { color: #67c23a; }
      &.completed .stat-number { color: #67c23a; }
      &.cancelled .stat-number { color: #f56c6c; }
    }
  }
  
  .table-card {
    .item-list {
      .item-tag {
        display: inline-block;
        padding: 2px 6px;
        margin-right: 5px;
        margin-bottom: 2px;
        background: #f0f2f5;
        border-radius: 3px;
        font-size: 12px;
      }
      
      .more-items {
        color: #999;
        font-size: 12px;
      }
    }
  }
  
  .card-view {
    .order-card {
      border: 1px solid #e4e7ed;
      border-radius: 8px;
      padding: 16px;
      margin-bottom: 16px;
      transition: all 0.3s;
      
      &:hover {
        box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
      }
      
      &.selected {
        border-color: #409eff;
        background-color: #f0f9ff;
      }
      
      .card-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 12px;
        
        .order-info {
          display: flex;
          align-items: center;
          gap: 10px;
          
          .order-no {
            font-size: 16px;
            font-weight: bold;
            color: #333;
          }
        }
      }
      
      .card-content {
        .customer-info {
          display: flex;
          justify-content: space-between;
          margin-bottom: 8px;
          
          .customer-name {
            font-weight: bold;
          }
          
          .customer-phone {
            color: #666;
            font-size: 14px;
          }
        }
        
        .service-info {
          display: flex;
          justify-content: space-between;
          align-items: center;
          margin-bottom: 8px;
          
          .amount {
            font-size: 16px;
            font-weight: bold;
            color: #f56c6c;
          }
        }
        
        .time-info {
          font-size: 12px;
          color: #666;
          margin-bottom: 8px;
          
          div {
            margin-bottom: 2px;
          }
        }
        
        .worker-info {
          font-size: 12px;
          color: #666;
        }
      }
      
      .card-actions {
        text-align: right;
        margin-top: 12px;
        padding-top: 12px;
        border-top: 1px solid #e4e7ed;
      }
    }
  }
  
  .pagination {
    margin-top: 20px;
    text-align: right;
  }
}
</style> 